package com.leyou.auth.service.impl;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description:
 * @author: YHL
 * @time: 2021/3/5 11:28
 */
@Service
public class UserAuthServiceImpl implements UserAuthService {
    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void userLogin(String username, String password, HttpServletResponse response) {
        UserDTO userDTO = this.userClient.queryUserByNameAndPass(username, password);


        UserDetail userDetail = new UserDetail();

        userDetail.setId(userDTO.getId());
        userDetail.setUsername(userDTO.getUsername());

        //使用jwt生成token
        String token = this.jwtUtils.createJwt(userDetail);


        //生成一份数据，存储user信息，数据最终存入cookie，技术使用JWT

        Cookie cookie = new Cookie("LY_TOKEN",token);

        //www.leyou.com
//        cookie绑定的域名
        cookie.setDomain("leyou.com");
//      从域名根路径开始匹配
        cookie.setPath("/");

        // -1 session级别，浏览器关闭时候会删除
//        最大有效时间

        cookie.setMaxAge(-1);

        //js等所有的脚本不能访问
        cookie.setHttpOnly(true);

        //在响应头中加一条记录，set-cookie:xxxxx
        response.addCookie(cookie);

    }

    @Override
    public void userLogOut(HttpServletRequest request, HttpServletResponse response) {    try {
        String token = CookieUtils.getCookieValue(request, "LY_TOKEN");

        //redis标记删除

        Payload payload = jwtUtils.parseJwt(token);

        //删除redis中对应的token标记信息
        this.redisTemplate.delete("ly:token:user:"+payload.getUserDetail().getId());
    } catch (Exception e) {
    }

        //创建一个新的cookie覆盖删除旧的cookie
        Cookie cookie = new Cookie("LY_TOKEN","");
        cookie.setDomain("leyou.com");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
}
